package com.likou;

public class q79 {

    public boolean exist(char[][] board, String word) {
        if (word == null || word.isEmpty()) {
            return true;
        }

        int gm = board.length;
        int gn = board[0].length;

        boolean[][] visited = new boolean[gm][gn];

        for (int i = 0; i < gm; i++) {
            for (int j = 0; j < gn; j++) {
                if (DFS(board, visited, word, 0, i, j)) {
                    return true;
                }
            }
        }

        return false;
    }

    private boolean DFS(char[][] board, boolean[][] visited, String word, int index, int m, int n) {
        if (index == word.length()) {
            return true;
        }
        int gm = board.length;
        int gn = board[0].length;
        if (m < 0 || m >= gm || n < 0 || n >= gn || visited[m][n]) {
            return false;
        }
        if (board[m][n] != word.charAt(index)) {
            return false;
        }

        visited[m][n] = true;
        boolean res = false;
        res |= DFS(board, visited, word, index + 1, m, n - 1); // 左边
        res |= DFS(board, visited, word, index + 1, m, n + 1); // 右边
        res |= DFS(board, visited, word, index + 1, m - 1, n); // 上边
        res |= DFS(board, visited, word, index + 1, m + 1, n); // 下边
        visited[m][n] = false;
        return res;
    }
}
